package me.xue.communityhealth.util;

import lombok.extern.log4j.Log4j2;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Log4j2
public final class FileUtil {

    private static final Object sLock = new Object();

    private FileUtil() {
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static String saveMultipartFile(MultipartFile multipartFile, String storagePath, String fileName) {
        log.info("Multipart file name: {} ", multipartFile.getOriginalFilename());
        String filePath = storagePath + File.separator + fileName;
        File file = new File(filePath);
        synchronized (sLock) {
            File backupFile = null;
            if (file.exists()) {//文件存在，则先备份原文件，保存成功后删除
                backupFile = new File(filePath + ".bak");
                file.renameTo(backupFile);
            }
            try {
                //如果文件存在，可能抛出异常
                Files.copy(multipartFile.getInputStream(), Paths.get(storagePath, fileName));
            } catch (IOException e) {
                log.error("保存文件失败", e);
                //头像保存失败，要将原头像还原
                if (backupFile != null && backupFile.exists()) {
                    backupFile.renameTo(file);
                }
            }
            if (backupFile != null && backupFile.exists()) {
                backupFile.delete();
            }
        }
        if (file.exists()) {
            return file.getName();
        }
        return null;
    }


}
